#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
优化后的内核检测器演示脚本
展示性能指标、改进的异常处理和策略有效性验证功能
"""

import sys
import os
import time

# 添加模块路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'modules'))

from modules.environment.detector import KernelDetector, EnvironmentAnalyzer

def main():
    """主演示函数"""
    print("="*70)
    print("                    优化后的内核检测器演示")
    print("="*70)
    
    # 创建检测器实例
    detector = KernelDetector()
    analyzer = EnvironmentAnalyzer()
    
    try:
        print("\n1. 执行内核版本检测...")
        start_time = time.time()
        kernel_info = detector.detect_kernel_version()
        detection_time = time.time() - start_time
        print(f"   检测完成，耗时: {detection_time:.3f}s")
        
        print("\n2. 分析系统能力...")
        start_time = time.time()
        capabilities = detector.analyze_capabilities()
        analysis_time = time.time() - start_time
        print(f"   分析完成，耗时: {analysis_time:.3f}s")
        
        print("\n3. 测试策略选择性能...")
        operation_types = detector.get_available_operation_types()
        print(f"   可用操作类型: {len(operation_types)} 种")
        
        for op_type in operation_types:
            start_time = time.time()
            strategy = detector.get_optimal_strategy(op_type)
            selection_time = time.time() - start_time
            if strategy:
                success_rate = strategy.get('success_rate', 0.0)
                print(f"   {op_type}: {strategy['primary']} (选择耗时: {selection_time:.3f}s, 成功率: {success_rate:.1%})")
        
        print("\n4. 执行完整环境分析...")
        start_time = time.time()
        analysis_result = analyzer.full_analysis()
        full_analysis_time = time.time() - start_time
        print(f"   完整分析完成，耗时: {full_analysis_time:.3f}s")
        
        print("\n5. 显示分析摘要...")
        analyzer.print_analysis_summary()
        
        print("\n6. 显示性能报告...")
        detector.print_performance_report()
        
        print("\n7. 测试异常处理...")
        try:
            # 故意触发一个错误来测试异常处理
            detector.kernel_info = {}  # 清空内核信息
            detector.get_optimal_strategy("invalid_operation_type")
        except Exception as e:
            print(f"   异常处理测试: 成功捕获异常 - {type(e).__name__}")
        
        print("\n8. 生成能力JSON报告...")
        try:
            json_report = detector.generate_capabilities_json()
            if json_report:
                print(f"   JSON报告生成成功，长度: {len(json_report)} 字符")
            else:
                print("   JSON报告生成失败")
        except Exception as e:
            print(f"   JSON报告生成异常: {e}")
        
        print("\n" + "="*70)
        print("                        演示完成")
        print("="*70)
        
        # 显示优化总结
        print("\n优化功能总结:")
        print("✓ 性能指标追踪 - 记录执行时间和成功率")
        print("✓ 改进的异常处理 - 使用自定义异常类和日志记录")
        print("✓ 策略有效性验证 - 检查策略要求和兼容性")
        print("✓ 优化的版本比较 - 使用packaging库进行精确版本比较")
        print("✓ 动态操作类型获取 - 不再使用硬编码列表")
        print("✓ 线程安全的性能指标 - 使用锁保护共享数据")
        print("✓ 详细的兼容性分析 - 提供改进建议和回退策略")
        
    except Exception as e:
        print(f"\n演示过程中发生错误: {e}")
        print(f"错误类型: {type(e).__name__}")
        return 1
    
    return 0

if __name__ == "__main__":
    exit_code = main()
    sys.exit(exit_code)